// pages/restaurant/shop/shopDetail/index.js
const app = getApp();

import { list as ShopList, find } from '../../../api/shop'
import { list as productList } from '../../../api/product'
import { addCart, getCart, update } from "../../../api/cart"
import { add, del,exists } from "../../../api/shopFavorites"
import { couponList, } from "../../../api/coupon"
const util = require('../../../utils/util.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        list: [],
        shoucangSuccessIconUrl:util.thumbnail(app.APP_OSSURL_API+"/dinnerBar/canyin/canyin-yishoucan.png",  48, 48),
        shoucangfailIconUrl:util.thumbnail(app.APP_OSSURL_API+"/dinnerBar/canyin/canyin-weishoucan.png", 48, 48),
        topBackgroundUrl: util.thumbnail(app.APP_OSSURL_API+"/dinnerBar/canyin/canyin-shopDetailBackground.png", 345, 750),
        shopLogoUrl: "",
        shopBottomHeight: "",
        selectedMenuId: "",
        selectedSecondMenuId: "",
        istopShow: false,
        IsbottomShow: false,
        istopTitle: "",
        istopMsg: "",
        // secondMenuBlankShow:false,

        secondMenuHeight: "",
        productInfoHeight: "",
        windowWidth: "",
        windowHeight: "",
        productModelHeightList: [], //记录商品模块的高度

        shopInfo: "",
        shopId: "",
        shopName: "",
        address: "",
        time: "",
        monthSale: 0,
        notice: "",

        discountList: [
            // { msg: "22减5" }, { msg: "22减5" }, { msg: "22减5" },
        ],
        shopCouponList: [
            // { type: "noThreshold", amount: 30, msg: "无门槛" },
            // // {type:"noThreshold", amount:30, msg:"无门槛"},
            // { type: "discount", amount: 30, msg: "满100可用" }
        ],
        productList: [],
        cartInfo: {},
        cartInfoToAttr: {},//传输给属性选择框的数据

        // 暂存滚动是的三条线的数据
        areaTop: "",
        areaLine: "",
        areabottom: "",
        scrollOff:false,
        statusBarHeight:"",
        status: "",
        navHeight: "",
        boxScrollTop:"", //外框的滑动距离
        ScrollTop:"",
        menuListIsScroll:false,
        productListIsScroll:false,
        signageHeight:"", //保存店铺信息的栏的高度
        shopFavoriteStatus:false, //店铺的收藏状态
        couponType:false, //优惠券信息的弹窗
        couponInfo:{},
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad:function(options){
        let _this = this
        _this.setNavSize()
        this.setData({ shopId: options.shopId, statusBarHeight: app.globalData.statusBarHeight, })
    },
    onShow: function (options) {
        let _this = this
        // _this.setNavSize()
          console.log("options-------------------------------");
                  console.log(options);
        // this.setData({ shopId: options.shopId, statusBarHeight: app.globalData.statusBarHeight, })
        this.getShopInfo(_this.data.shopId,()=>{
            _this.getproductInfoList(_this.data.mchId)
        })
        if(app.globalData.token != null){
        this.getShopFavoriteStatus(_this.data.shopId)
        }
        this.getCart()
        this.selectComponent("#settlement").getCart()
        this.selectComponent("#settlement").getCount()
        wx.getSystemInfo({
            success: function (res) {
                //   console.log(res.windowWidth);
                //   console.log(res.windowHeight);
                _this.data.windowWidth = res.windowWidth
                _this.data.windowHeight = res.windowHeight
                let headerHeight = _this.data.navHeight + _this.data.status
                //   console.log("头部的高度");
                //   console.log(headerHeight);
                let height = (res.windowHeight - headerHeight) * 750 / res.windowWidth - 186
                //   console.log("height--"+height);
                _this.setData({
                    shopBottomHeight: height
                })
            },
        })
    },

    // 控制优惠券弹窗显示
    signagetap(){
        let _this = this
        this.setData({
            couponType: true
        })
    },

    // 控制优惠券弹窗关闭
    cancleClick(){
        let _this = this
        this.setData({
            couponType: false
        })
    },

    //检测用户的登陆状态
  checkLogin(callback) {
    console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
    if (app.globalData.token == null) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      if (callback) {
        callback()
      }
    }
  },

  //联系商家
  phoneShop(){
      let _this = this
        if (_this.data.telephone) {
        wx.makePhoneCall({
          phoneNumber: _this.data.telephone // 仅为示例，并非真实的电话号码
        })
      }
  },

    //返回键
    navTo() {
        let p = getCurrentPages().length;
        if (p <= 1) {
                wx.switchTab({
                        url: '/pages/index/index',
                })
        } else {
                wx.navigateBack({
                        delta: 1
                })
        }
},

    //查询平台优惠券列表
    getcouponList(){
        let _this = this
        let params = {
            mchId:app.globalData.mchId
        }
        couponList(params).then(
            (res)=>{
                console.info("优惠券信息------")
                console.info(res)
                if (res.type == 'success') {
                    _this.setData({
                        shopCouponList :res.data.data    
                    })
                }
            }
        ).catch( )
    },

    //查询是否收藏店铺
    getShopFavoriteStatus(shopId){
        let params = {
            shopId:shopId
        }
        exists(params).then(
            (res)=>{
                if (res.type == 'success') {
                    if(res.data == 1){
                        this.setData({
                            shopFavoriteStatus:true
                        })
                    }else{
                        this.setData({
                            shopFavoriteStatus:false
                        })
                    }
                }
            }
        ).catch( )
    },

    // 添加店铺收藏
    addShopFavorite(){
        this.checkLogin(()=>{
            let data = {
                shopId:this.data.shopId
            }
            if(this.data.shopFavoriteStatus){
                del(data).then(
                    (res)=>{
                        if (res.type == 'success') {
                            wx.showToast({
                                title: "取消收藏成功",
                                icon:"none"
                              })
                              this.setData({
                                shopFavoriteStatus:false
                            })
                        }
                    }
                ).catch( )
            }else{
                add(data).then(
                    (res)=>{
                        if (res.type == 'success') {
                            wx.showToast({
                                title: "收藏成功",
                                icon:"none"
                              })
                              this.setData({
                                shopFavoriteStatus:true
                            })
                        }
                    }
                ).catch( )
            }
        })
    },

    // 获取商店信息
    getShopInfo(shopId,callback) {
        let _this = this
        find(shopId).then(
            res => {
                console.info("获取商店信息--")
                console.info(res)
                if (res.type == 'success') {
                    // _this.data.shopInfo = res.data.shop
                    // console.info("***********************************************")
                    // console.info(res.data.shop.shippingConfig)
                    // let shippingConfig = JSON.parse(res.data.shop.shippingConfig)
                    // console.info(shippingConfig)
                    // console.info("***********************************************")
                    let time = ""
                    let workBeginTime = ""
                    let workEndTime = ""
                    if(!util.isNull(res.data.shop.shippingConfig)){
                        let shippingConfig = JSON.parse(res.data.shop.shippingConfig)
                        time = shippingConfig.workBeginTime + " - " + shippingConfig.workEndTime
                        if(!util.isNull(shippingConfig.workBeginTime)&&!util.isNull(shippingConfig.workEndTime)){
                            workBeginTime = shippingConfig.workBeginTime
                            workEndTime = shippingConfig.workEndTime
                        }
                    }

                    _this.setData({
                        shopInfo:res.data.shop,
                        mchId: res.data.shop.mchId,
                        shopName: res.data.shop.name,
                        address: res.data.shop.address,
                        shopLogoUrl: util.thumbnail(res.data.shop.logo, 150, 150),
                        monthSale: res.data.shop.monthSale,
                        discountList: res.data.shop.promotions,
                        shopCouponList: res.data.shop.coupons,
                        time:time,
                        telephone:res.data.shop.telephone,
                        workBeginTime:workBeginTime,
                        workEndTime:workEndTime
                    })
                    if(callback){
                        callback(res.data)
                    }
                    wx.createSelectorQuery().select('#signage').boundingClientRect(rect => {
                        console.info("secondMenu-rect--" + rect)
                        _this.data.signageHeight = rect.height * 750 / _this.data.windowWidth;
                    }).exec();
                }
            }
        ).catch(error => { })
    },

    //设置头部标题栏的高度
    setNavSize: function () {
        var that = this,
          sysinfo = wx.getSystemInfoSync(),
          statusHeight = sysinfo.statusBarHeight,
          isiOS = sysinfo.system.indexOf('iOS') > -1,
          navHeight;
          console.log(sysinfo)
        if (!isiOS) {
          navHeight = 48;
        } else {
          navHeight = 44;
        }
        that.setData({
          status: statusHeight,
          navHeight: navHeight
        })
        console.info("status--"+that.data.status)
        console.info("navHeight--"+that.data.navHeight)
      },

    //获取商品信息
    getproductInfoList(mchId) {
        let _this = this
        let params = { mchId: mchId, pageSize: 1000 }
        productList(params).then(
            res => {
                //   console.log("productList--" + JSON.stringify(res))
                if (res.type == 'success') {
                    _this.formateProductList(res.data.data)
                }
            }
        ).catch(error => { })
    },

    //单商品模块的回调更新购物车信息
    updateCart(data) {
        console.info("data")
        console.info(data)
        this.getCart(() => {
            this.selectComponent("#settlement").cartHandler(data.detail)
        })

    },

    //属性选择模块的回调更新购物车信息
    reloadCartFromAttr(attrData) {
        console.info("属性选择模块attrData")
        console.info(attrData)
        let _this = this
        this.getCart(
            (data) => {
                console.info("属性选择模块的回调更新购物车信息")
                console.info(data)
                _this.selectComponent("#settlement").cartHandlerWithoutAnimation()
            })

    },

    //获取购物车信息
    getCart(callback) {
        // console.info(shopId)
        // console.info(typeof(parseInt(shopId)) + parseInt(shopId))
        let params = {
            // shopId:parseInt(shopId),
            shopId: this.data.shopId,
            uuid: app.globalData.uuid
        }
        getCart(params).then(
            res => {
                if (res.type == 'success') {
                    this.setData({
                        cartInfo: res.data.cart
                    })
                    if (callback) {
                        callback(res.data)
                    }
                }
            }
        ).catch(error => { })
    },

    //整理商品的分类数据
    formateProductList(data) {
        let _this = this
        if (data.length > 0) {
            let productCategoryIds = []
            data.map(item => {
                productCategoryIds.push(item.productCategoryId)
                item.thumbnail = util.thumbnail(item.thumbnail, 160, 160)
            })
            productCategoryIds = Array.from(new Set(productCategoryIds))
            // console.info("productCategoryIds")
            // console.info(productCategoryIds)
            let productList = []
            productCategoryIds.map((item, index) => {
                let productListItem = {}
                productListItem.list = []
                data.map((item1, index1) => {
                    if (item == item1.productCategoryId) {
                        productListItem.id = item1.productCategoryId
                        productListItem.title = item1.productCategoryName ? item1.productCategoryName : "其他分类"
                        productListItem.status = index == 0 ? true : false
                        productListItem.msg = ""
                        productListItem.secondMenuBlankShow = false
                        productListItem.list.push(item1)
                    }
                })
                productList.push(productListItem)
            })
            // console.info("productList")
            // console.info(productList)
            _this.setData({
                productList: productList
            })
            _this.init(productList)
        }
    },

    //初始化商品的数据
    init(productList) {
        let _this = this
        let query = wx.createSelectorQuery();
        query.select('.secondMenu').boundingClientRect(rect => {
            console.info("secondMenu-rect--" + rect)
            _this.data.secondMenuHeight = rect.height * 750 / _this.data.windowWidth;
        }).exec();
        query.select('.productModel').boundingClientRect(rect => {
            console.info("productModel-rect--" + rect)
            _this.data.productInfoHeight = rect.height * 750 / _this.data.windowWidth;
            let heightStorage = 0
            if (productList.length > 0) {
                productList.map(item => {
                    // console.info("heightStorage--"+heightStorage)
                    let listItem = {}
                    item.top = heightStorage - 1
                    if (item.list.length > 0) {
                        heightStorage += _this.data.secondMenuHeight + _this.data.productInfoHeight * item.list.length
                    } else {
                        heightStorage += _this.data.secondMenuHeight
                    }
                    item.line = heightStorage
                    heightStorage += _this.data.secondMenuHeight
                    item.bottom = heightStorage - 1
                })
            }
            console.info("productList--")
            console.info(productList)
            _this.setData({
                productList: productList,
                areaTop: productList[0].top,
                areaLine: productList[0].line,
                areabottom: productList[0].bottom,
                currentIndex: 0,
            })
        }).exec();
    },

    //左侧目录的点击事件
    menuListItemClick(e) {
        this.menuChange(e.currentTarget.dataset.item.id)
    },

    //左侧目录的切换
    menuChange(id) {
        this.setData({
            productListIsScroll: true,
        })
        let productList = this.data.productList
        if (productList.length > 0) {
            productList.map((item) => {
                item.status = false
                if (item.id == id) {
                    item.status = true
                }
            })
        }
        this.setData({
            productList: productList,
            selectedSecondMenuId: id,
            istopShow: false,
        })
        if(this.data.boxScrollTop < this.data.signageHeight ){
            this.setData({
                productListIsScroll: false,
            })
        }
    },

    boxBindscroll(e){
        console.info("外框的总高度" + (this.data.signageHeight))
        let scrollTop = e.detail.scrollTop * 750 / this.data.windowWidth
        console.info("外框" + scrollTop)
        this.data.boxScrollTop = scrollTop
        if(scrollTop >= this.data.signageHeight ){
            if(!this.data.productListIsScroll){
                console.info("我变成true")
                this.setData({
                    menuListIsScroll:true,
                    productListIsScroll:true
                })
            }
        }else if(scrollTop < 10){
            if(this.data.ScrollTop>0){
                if(!this.data.productListIsScroll){
                    console.info("我变成true")
                    this.setData({
                        menuListIsScroll:true,
                        productListIsScroll:true
                    })
                }
            }
        }else{
            if(this.data.productListIsScroll){
                console.info("我变成false")
                this.setData({
                    menuListIsScroll:false,
                    productListIsScroll:false
                })
            }
        }
    },

    // touchmove(){
    //     console.info("我。。。。。。。")
    // },

    //商品滚动事件
    bindscroll(e) {
        // console.info("--"+e.detail.scrollTop)
        // this.setData({
        //     boxScrollTop:  e.detail.scrollTop,
        //     ScrollTop:0
        // })
        let scrollTop = e.detail.scrollTop * 750 / this.data.windowWidth
        // console.info("先计算" + scrollTop)
        this.data.ScrollTop = scrollTop
        if(this.data.ScrollTop < 5){
            this.setData({
                productListIsScroll:false
            })
        }
        let productList = this.data.productList
        // console.info("this.data.areaTop" + this.data.areaTop)
        // console.info("this.data.areaLine" + this.data.areaLine)
        // console.info("this.data.areabottom" + this.data.areabottom)
        if (scrollTop < this.data.areaTop || scrollTop > this.data.areabottom) {
            // console.info("我被执行了" + scrollTop)
            if (productList.length > 0) {
                productList.map((item, index) => {
                    item.secondMenuBlankShow = false
                    item.status = false
                    if (scrollTop >= item.top && scrollTop < item.bottom) {
                        this.setData({
                            areaTop: item.top,
                            areaLine: item.line,
                            areabottom: item.bottom,
                            currentIndex: index,
                            productList: productList,
                            scrollOff:true
                        })
                    }
                })
            }
        }else{
            if(this.data.scrollOff){
                productList[this.data.currentIndex].status = true
                this.setData({
                    selectedMenuId: productList[this.data.currentIndex].id,
                    // istopShow: false,
                    productList: productList,
                    scrollOff:false
                })
            }
            // if (scrollTop >= this.data.areaLine && scrollTop < this.data.areabottom) {
            //     // console.info("进入主体" + scrollTop)
            //     if(this.data.istopShow){
            //         productList[this.data.currentIndex].secondMenuBlankShow = true
            //         this.setData({
            //             selectedMenuId: productList[this.data.currentIndex].id,
            //             istopShow: false,
            //             productList: productList
            //         })
            //     }
            // }
            // if (scrollTop >= this.data.areaTop && scrollTop < this.data.areaLine) {
            //     // console.info("进入主体" + scrollTop)
            //     if(!this.data.istopShow){
            //         productList[this.data.currentIndex].secondMenuBlankShow = false
            //         this.setData({
            //             selectedMenuId: productList[this.data.currentIndex].id,
            //             istopTitle: productList[this.data.currentIndex].title,
            //             istopMsg: productList[this.data.currentIndex].msg,
            //             istopShow: true,
            //             productList: productList
            //         })
            //     }
            // }
        }
    },

    //显示商品属性选择框
    showAttrDialog(e) {
        console.info("显示商品属性选择框")
        console.info(e.detail)
        this.selectComponent("#attributeDialog").showAttrDialog(e.detail, this.data.cartInfo)
    }
})